/**
 * 选择择部门
 * 
 */

import { ApartmentOutlined, FolderOpenOutlined, HomeOutlined, RightOutlined } from "@ant-design/icons";
import { Breadcrumb, Button, Drawer, Input, List } from "antd";
import React from "react";
import useDepartments from "./hooks/useDepartments";
import styles from './index.module.less';
import { useVisible } from "@/tools/hooks";


export interface ISelectUserProps {

    /** 择部门数据改变 */
    onChange?: (value: any) => void;

    /** 择部门数据 */
    value?: any;
}

export function SelectDepartments(props: ISelectUserProps) {

    const { open: visible, onClose, onOpen } = useVisible();

    const { setStart, departmentsList, parent, setParent, go, loading } = useDepartments();

    const [value, setValue] = React.useState<any>();

    const onClickDep = React.useCallback((dep: any) => {
        setValue(dep);
        props?.onChange?.(dep);
        onClose();
    }, [onClose, props])

    React.useEffect(() => {
        setValue(props.value)
    }, [props.value])

    React.useEffect(() => {
        setParent([])
        setStart(visible);
    }, [setParent, setStart, visible]);

    return (
        <>
            <Input readOnly placeholder="点击选择部门" onClick={onOpen} value={value?.name} suffix={<ApartmentOutlined style={{ color: 'rgba(0, 0, 0, 0.25)' }} />} />
            <Drawer title="选择部门" bodyStyle={{ display: 'flex', flexDirection: 'column' }} placement="right" onClose={onClose} visible={visible} destroyOnClose>

                <Breadcrumb className={styles.dreadcrumb} separator=">" >
                    <Breadcrumb.Item onClick={() => { setParent([]) }}>
                        <HomeOutlined />
                    </Breadcrumb.Item>
                    {
                        parent.map(e => {
                            return (
                                <Breadcrumb.Item onClick={() => { go(e) }} >
                                    {e.name}
                                </Breadcrumb.Item>
                            )
                        })
                    }
                </Breadcrumb>

                <List
                    bordered
                    loading={loading.length > 0}
                    dataSource={departmentsList}
                    renderItem={dep => {
                        return (
                            <List.Item actions={[<Button type="link" onClick={() => { go(dep) }} icon={<RightOutlined />} />]}>
                                <Button icon={<FolderOpenOutlined />} type="link" style={{ padding: 0 }} onClick={() => { onClickDep(dep) }} >{dep.name}</Button>
                            </List.Item>
                        )
                    }}
                />
            </Drawer>
        </>
    )
}